<?php
/**
 * Created by PhpStorm.
 * User: wangxiaodan
 * Date: 2017/5/15
 * Time: 下午4:56
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Http\Requests;
use Carbon\Carbon;

class CourseController extends Controller
{
    public function index(){
        $courses = Course::paginate(config('constants.page_num'));
        return view('admin.course.index', compact('courses'));
    }

    public function create($subject_id){
        return view('admin.course.create', compact('subject_id'));
    }

    public function store(Requests\CourseRequest $request){
        $data = $request->all();
        $data['week'] = Carbon::parse($data['week'])->weekOfYear;
        $result = Course::create($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'admin/course/findmore/'.$data['subject_id'])));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function edit($id){
        $course = Course::findOrFail($id);
        return view('admin.course.edit', compact('course'));
    }

    public function update(Requests\CourseRequest $request, $id){
        $course = Course::findOrFail($id);
        $data = $request->all();
        if (strlen($data['week']) > 2){
            $data['week'] = Carbon::parse($data['week'])->weekOfYear;
        }
        $result = $course->update($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'admin/course/findmore/'.$course->subject_id)));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $course = Course::findOrFail($id);
        if ($course->delete()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }

    public function findCourse(){
        $courseArr = Course::get()->toArray();
        foreach ($courseArr as $value){
            $result[] = array(
                'value' => $value['name'],
                'id'   => $value['id'],
            );
        }
        return json_encode($result);
    }

    public function findCourseMore($subject_id){
        $courses = Course::where("subject_id", $subject_id)->get();
        return view('admin.course.index', compact('courses', 'subject_id'));
    }
}